package com.woniu.filter;

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

/**
 * gateway限流过滤器
 * 根据id限流
 */

@Component
@Order(-100)
public class GatewayRateLimitFilter implements GlobalFilter {

    //定义桶的容积
    private int buckerSize = 5;
    private static final Map<String, Bucket> MAPS = new ConcurrentHashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String ip = exchange.getRequest().getURI().getHost();
        Bucket bucket = MAPS.computeIfAbsent(ip, new Function<String, Bucket>() {
            @Override
            public Bucket apply(String s) {
                return createBucket();
            }
        });
        if (bucket.tryConsume(1)){
            System.out.println("==========");
            //拿到了令牌,放行
            return chain.filter(exchange);
        }else {
            String jsonStr = "{\"status\":\"400\", \"msg\":\"to many try,please next try\"}";
            byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Flux.just(buffer));
        }
    }

    /**
     * 创建一个桶
     * 非贪婪式创建令牌
     * @return
     */
    private Bucket createBucket(){
        Refill filler = Refill.intervally(5, Duration.ofSeconds(1));
        Bandwidth limit = Bandwidth.classic(buckerSize, filler);
        return Bucket4j.builder().addLimit(limit).build();
    }
}
